package com.hb.common.runner;

import com.hb.common.dto.DbBackupTask;
import com.hb.common.service.DbBackupTaskService;
import com.hb.common.util.CommonUtil;
import com.hb.common.util.JarUtil;
import com.hb.common.util.PathPermissions;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Component
public class DbBackupRunner implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(DbBackupRunner.class);

    @Resource
    private PathPermissions pathPermissions;
    @Resource
    private DbBackupTaskService dbBackupTaskService;

    @Override
    public void run(ApplicationArguments args) {
        try {
            // 初始化数据库程序文件
            this.initDbProgram();
            // 初始化data.properties
            this.initDataProperties();
            // 初始化定时任务
            this.initTask();

            log.info("数据库备份还原 初始化成功！");
        } catch (Exception e) {
            log.error("数据库备份还原 初始化失败！{}", e.getMessage());
        }
    }

    /**
     * 初始化数据库程序文件
     */
    public void initDbProgram() {
        try {
            InputStream in = JarUtil.getInputStream(DbBackupRunner.class, "dbProgram.zip");
            CommonUtil.unzipDbProgram(in, pathPermissions.getConfigPath());
        } catch (Exception ignored) {
        }
    }

    /**
     * 初始化定时任务
     */
    public void initTask() {
        // 获取已启用的定时任务
        List<DbBackupTask> taskList = dbBackupTaskService.selectList().getData();
        for (DbBackupTask task : taskList) {
            dbBackupTaskService.addTask(task);
        }
    }

    /**
     * 初始化data.properties
     */
    public void initDataProperties() {
        Path dirPath = Paths.get(pathPermissions.getConfigPath());
        try {
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
            }
            Path path = Paths.get(pathPermissions.getConfigPath() + "/data.properties");
            if (!Files.exists(path)) {
                Files.createFile(path);
            }
        } catch (Exception e) {
            log.error("Error creating file: {}", e.getMessage(), e);
        }
    }
}
